package com.honeymoondesert.crawler;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;

import com.crawler.Crawler;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.honeymoondesert.analyzer.AddressAnalyzer;
import com.honeymoondesert.util.MapUtil;
import com.honeymoondesert.util.PatternHelper;
import com.honeymoondesert.util.TranslateUrl;

public class StoreInfo {
	public String storeId;
	public String storeUrl;
	Document storeDoc=null;
	String date;
	List<String> competitorUrls=null;
	List<String> surroundUrls=null;
	List<JsonObject> dishes=null;	//推荐菜
	List<JsonObject> impression=null;	//大家认为
	List<JsonObject> comments=null;		//点评
	
	public StoreInfo(String storeUrl) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date now =new Date();
		this.date= sdf.format(now);
		this.storeUrl=storeUrl;
		this.storeId=storeUrl.substring(storeUrl.lastIndexOf("/shop/")+"/shop/".length());
		Crawler storeCrawler=new Crawler(this.storeUrl);
		if(storeCrawler.loadPage()){
			storeDoc=storeCrawler.getDoc();
		}
	}
	/**
	 * 获取点评
	 * @return
	 */
	
	/**
	 * 获取大家印象
	 * @return
	 */
	public List<JsonObject> getImpression() {
		if(impression==null){
			impression=new ArrayList<JsonObject>();
			//好评
			String cssQuery="#comment .content span.good a";
			Elements elements=storeDoc.select(cssQuery);
			
			for (Element element : elements) {
				String tmpText=element.text();
				String name=tmpText.substring(0,tmpText.indexOf("("));
				JsonObject item=new JsonObject();
				item.addProperty("storeId", storeId);
				item.addProperty("name", name);
				item.addProperty("count", PatternHelper.getIntNum(tmpText));
				item.addProperty("category", "good");
				item.addProperty("date", date);
				impression.add(item);
			}
			//差评
			cssQuery="#comment .content span.bad a";
			elements=storeDoc.select(cssQuery);
			for (Element element : elements) {
				String tmpText=element.text();
				String name=tmpText.substring(0,tmpText.indexOf("("));
				JsonObject item=new JsonObject();
				item.addProperty("storeId", storeId);
				item.addProperty("name", name);
				item.addProperty("count", PatternHelper.getIntNum(tmpText));
				item.addProperty("category", "bad");
				item.addProperty("date", date);
				impression.add(item);
			}
		}
		return impression;
	}
	
	/**
	 * 获取推荐菜
	 * @return
	 */
	public List<JsonObject> getDishes() {
		if(dishes==null){
			dishes=new ArrayList<JsonObject>();
			String cssQuery="div#shop-tabs script.J-panels";
			Elements elements=storeDoc.select(cssQuery);
			String html=elements.toString();
			html=html.substring(html.indexOf(">")+1);
			html=html.substring(0,html.indexOf("</script>"));
			Document tmpDoc=Jsoup.parse(html);
			elements=tmpDoc.select("p.recommend-name a");
			for (Element element : elements) {
				JsonObject item=new JsonObject();
				item.addProperty("storeId", storeId);
				item.addProperty("name", element.attr("title"));
				String count=element.getElementsByClass("count").text();
				count=count.substring(1,count.length()-1);
				item.addProperty("count", count);
				item.addProperty("date", date);
				dishes.add(item);
			}
		}
		return dishes;
	}
	/**
	 * 获取周边店面的Url
	 * @return
	 */
	public List<String> getSurroundUrls() {
		if(surroundUrls==null){
			surroundUrls=new ArrayList<String>();
			String cssQuery="div.breadcrumb a";
			Elements elements=storeDoc.select(cssQuery);
			Element element=elements.get(2);	
			String cptListUrl=element.attr("href"); //获取竞争对手List页面的URL
			Boolean next=true;
			do{
				Crawler cptListCrawler=new Crawler(cptListUrl);
				if(!cptListCrawler.loadPage())return null;
				Document cptListDoc=cptListCrawler.getDoc();
				surroundUrls.addAll(pushStoreToList(cptListDoc));	//获取页面中的所有店家链接
				String cssq="div.page a.next";
				Elements nextElements=cptListDoc.select(cssq);		//获取下一页按钮
				if(!nextElements.isEmpty()){
					cptListUrl=nextElements.attr("href");
					cptListUrl=TranslateUrl.getUrl(cptListUrl);
				}else {
					next=false;
				}
				
			}while(next);
			
			
			
		}

		surroundUrls.remove(storeUrl);

		return surroundUrls;
	}
	/**
	 * 获取竞争对手店面的Url
	 * @return
	 */
	public List<String> getCompetitorUrls() {
		if(competitorUrls==null){
			competitorUrls=new ArrayList<String>();
			String cssQuery="div.breadcrumb a";
			Elements elements=storeDoc.select(cssQuery);
			Element element=elements.get(3);	
			String cptListUrl=element.attr("href"); //获取竞争对手List页面的URL
			Boolean next=true;
			do{
				Crawler cptListCrawler=new Crawler(cptListUrl);
				cptListCrawler.loadPage();
				Document cptListDoc=cptListCrawler.getDoc();
				competitorUrls.addAll(pushStoreToList(cptListDoc));	//获取页面中的所有店家链接
				String cssq="div.page a.next";
				Elements nextElements=cptListDoc.select(cssq);		//获取下一页按钮
				if(!nextElements.isEmpty()){
					cptListUrl=nextElements.attr("href");
					cptListUrl=TranslateUrl.getUrl(cptListUrl);
				}else {
					next=false;
				}
				
			}while(next);
			
			
			
		}
		competitorUrls.remove(storeUrl);
		return competitorUrls;
	}
	private List<String> pushStoreToList(Document doc){
		List<String> resultList=new ArrayList<String>();
		String cssQuery="div#shop-all-list div.tit>a[data-hippo-type=shop]";
		Elements elements=doc.select(cssQuery);
		for (Element cpt : elements) {
//			if(cpt.className().equals("shop-branch"))continue;	//跳过分店a链接
			String urlString=cpt.attr("href");
			resultList.add(TranslateUrl.getUrl(urlString));
		}
		return resultList;
	}
	
	
	/**
	 * 根据页面Url，爬取店面信息
	 * @return
	 */
	public JsonObject crawlStoreInfo() {
		JsonObject store=new JsonObject();
		try{
			//城市
			String city = getCity();
			//商区
			String businessArea = getBusinessArea();
			//名称
			String storeName=getStoreName();
			//区县
			String district=getDistrict();
			//地址
			String address=getAddress();
			//电话
			String tel=getTel();
			//总评分
			String score=getScore();
			//评论数
			Integer commentNum=getCommentNum();
			//人均
			Integer advPrice=getAdvPrice();
			//口味
			Double taste=getTaste();
			//环境
			Double enviroment=getEnviroment();
			//服务
			Double service=getService();
			//得分分布
			String distribution=getDistribution();
			//坐标
			MapUtil mu=new MapUtil();
			
			JsonObject roadinfo=AddressAnalyzer.analyze(address);
			//路名
			String road=roadinfo.get("road")==null?"":roadinfo.get("road").getAsString();
			//号牌
			String number=roadinfo.get("number")==null?"":roadinfo.get("number").getAsString();
			//楼层
			String floor=roadinfo.get("floor")==null?"":roadinfo.get("floor").getAsString();
			JsonObject coord;
			try {
				coord=mu.lngAndLat(address, city);
				if(coord.get("lng")==null){
					coord.addProperty("lng", "");
					coord.addProperty("lat", "");
				}
			} catch (Exception e) {
				// TODO: handle exception
				coord=new JsonObject();
				coord.addProperty("lng", "");
				coord.addProperty("lat", "");
			}
			
			
			store.addProperty("id", storeUrl.substring(storeUrl.lastIndexOf("/shop/")+"/shop/".length()));
			store.addProperty("storeName", storeName);
			store.addProperty("district", district);
			store.addProperty("address", address);
			store.addProperty("tel", tel);
			store.addProperty("commentNum", commentNum);
			store.addProperty("score", score);
			store.addProperty("distribution", distribution);
			store.addProperty("advPrice", advPrice);
			store.addProperty("taste", taste);
			store.addProperty("enviroment", enviroment);
			store.addProperty("service", service);
			store.addProperty("date", date);
			store.addProperty("storeUrl", storeUrl);
			store.addProperty("lng", coord.get("lng").getAsString());
			store.addProperty("lat", coord.get("lat").getAsString());
			store.addProperty("city", city);
			store.addProperty("businessArea", businessArea);
			store.addProperty("road", road);
			store.addProperty("number", number);
			store.addProperty("floor", floor);
			
		}catch(Exception ex){
			System.out.println("load Url:"+storeUrl+" 发生错误!可能该店没有评分。");
			ex.printStackTrace();
		}
		return store;
	}

	private String getDistribution() {
		String result="";
		String cssQuery="div#shop-score ul.stars li";
		Elements elements = storeDoc.select(cssQuery);
		if(!elements.isEmpty()){
			for(int i=0;i<elements.size();i++){
				Element element=elements.get(i);
				String score=element.ownText();
				result+="|"+score;
			}
		}else {
			cssQuery=".comment-summary ul.status-list li";
			elements = storeDoc.select(cssQuery);
			for(int i=0;i<elements.size();i++){
				Element element=elements.get(i);
				String score=element.select(".progress-bar a").text();
				score=String.valueOf(PatternHelper.getIntNum(score));
				result+="|"+score;
			}
		}
		if(result.startsWith("|")){
			result=result.substring(1);
		}
		return result;
	}
	private Double getService() {
		String cssQuery="div.brief-info .item";
		Elements elements = storeDoc.select(cssQuery);
		String result=null;
		for (Element element : elements) {
			if(element.text().indexOf("服务")>=0){
				result=element.text();
			}
		}
		return PatternHelper.getDoubleNum(result);
	}

	private Double getEnviroment() {
		String cssQuery="div.brief-info .item";
		Elements elements = storeDoc.select(cssQuery);
		String result=null;
		for (Element element : elements) {
			if(element.text().indexOf("环境")>=0){
				result=element.text();
			}
		}
		return PatternHelper.getDoubleNum(result);
	}

	private Double getTaste() {
		String cssQuery="div.brief-info .item";
		Elements elements = storeDoc.select(cssQuery);
		String result=null;
		for (Element element : elements) {
			if(element.text().indexOf("口味")>=0){
				result=element.text();
			}
		}
		return PatternHelper.getDoubleNum(result);
	}

	private Integer getAdvPrice() {
		String cssQuery="div.brief-info .item";
		Elements elements = storeDoc.select(cssQuery);
		String result=null;
		for (Element element : elements) {
			if(element.text().indexOf("人均")>=0){
				result=element.text();
			}
		}
		if(result==null){
			cssQuery="div.comment-rst .Price";
			Element element = storeDoc.select(cssQuery).first().parent();
			result=element.text();
		}
		return PatternHelper.getIntNum(result);
	}

	private String getScore() {
		String cssQuery="div.brief-info span";
		Elements elements = storeDoc.select(cssQuery);
		if(elements.isEmpty()){
			cssQuery="div.comment-rst span.item-rank-rst";
			elements = storeDoc.select(cssQuery);
		}
		String result=elements.get(0).attr("title");
		return result;
	}

	private Integer getCommentNum() {
		String cssQuery="div.brief-info span.item";
		Elements elements = storeDoc.select(cssQuery);
		String result="0";
		if(!elements.isEmpty()){
			result=elements.get(0).text();
			if(result.indexOf("条")>=0){
				result=result.substring(0,result.indexOf("条"));
			}else {
				result="0";
			}
		}else {
			cssQuery="div.comment-rst a.count span";
			elements = storeDoc.select(cssQuery);
			result=elements.text();
		}
		
		return Integer.parseInt(result);
	}

	private String getTel() {
		String cssQuery=".expand-info.tel span.item";
		Elements element = storeDoc.select(cssQuery);
		String result=element.text();
		if(result.equals("")){
			cssQuery=".shop-info-content [itemprop=tel]";
			element = storeDoc.select(cssQuery);
			result=element.text();
		}
		return result;
	}

	private String getDistrict() {
		String cssQuery=".expand-info.address a";
		Element element = storeDoc.select(cssQuery).first();
		if(element==null){
			cssQuery=".desc-list .shopDeal-Info-address a .region";
			element = storeDoc.select(cssQuery).first();
		}
		if (element==null) {
			cssQuery = "div.breadcrumb a";
			element = storeDoc.select(cssQuery).get(1);
		}
		String result=element.text();
		return result;
	}

	private String getAddress() {
		String cssQuery=".expand-info.address span.item";
		Elements element = storeDoc.select(cssQuery);
		String result=element.text();
		if(result.equals("")){
			cssQuery=".shopDeal-Info-address span[itemprop=street-address]";
			element = storeDoc.select(cssQuery);
			result=element.text();
		}
		return result;
	}

	private String getStoreName() {
		String cssQuery="h1.shop-name";
		Element element = storeDoc.select(cssQuery).first();
		String result="";
		if(element!=null){
			result=element.html();
			//去除A标签后的快捷链接
			result=result.substring(0,result.indexOf("<a"));
		}else {
			cssQuery="div.shop-name .shop-title";
			element = storeDoc.select(cssQuery).first();
			result=element.text();
		}
		
		return result;
	}
	
	private String getCity(){
		String cssQuery = "a.city.J-city";
//		String cssQuery = "#page-header div.container a";
		Elements element = storeDoc.select(cssQuery);
		String result = "";
		if (element!=null) {
			result = element.text();
		}
		return result;
	}
	
	private String getBusinessArea(){
		String cssQuery = "div.breadcrumb a";
		Element element = storeDoc.select(cssQuery).get(2);
		String result = "";
		if (element!=null) {
			result = element.html();
		}
		return result;
	}
	
	
	
}
